<template>
    <div class="edit-down-table">
        <vxe-pulldown class="edit-down-pulldown" ref="xDown" transfer>
            <template>
                <vxe-input class="edit-down-input" v-model="row[column.property]"
                           suffix-icon="fa fa-search" @keyup="keyupEvent"
                           @click="clickEvent" @focus="clickEvent1"
                           @suffix-click="suffixClick"/>
            </template>
            <template v-slot:dropdown>
                <div class="edit-down-wrapper">
                    <vxe-grid ref="xGrid" :size="size" auto-resize height="auto"
                              stripe border fit highlight-current-row :keyboard-config="{ isArrow: true }"
                              :loading="loading" :pager-config="tablePage" :data="tableData"
                              :columns="tableColumn" @cell-click="selectEvent" @page-change="pageChangeEvent"/>
                </div>
            </template>
            <vxe-modal class="vxe-table--ignore-clear edit-popup-box" :width="dWidth" :height="dHeight"
                       escClosable :title="title" v-model="modalVisible">
                <template v-slot>
                    <div style="display:flex;align-items: flex-start;justify-content: flex-start;height: 100%">
                        <virtual-node :render="dLeft" :params="params" v-if="dLeft" />
                        <vxe-grid ref="xGrid" height="auto" :size="size" stripe border fit
                                  :loading="loading" highlight-current-row :keyboard-config="{ isArrow: true }"
                                  :pager-config="tablePage" :columns="realModelTableColumn" :data="tableData"
                                  @cell-click="selectEvent" @page-change="pageChangeEvent" :style="gridStyle">
                            <template v-slot:toolbar>
                                <vxe-toolbar>
                                    <template v-slot:buttons v-if="dButtons">
                                        <virtual-node :render="dButtons" :params="params" />
                                    </template>
                                    <template v-slot:tools>
                                        <vxe-input v-model="searchVal" size="mini" placeholder="搜索"
                                                   style="height: 24px;width: 300px;"/>
                                        <el-button icon="el-icon-search" @click="getData(modalVisible)"
                                                   style="margin-left: 5px"/>
                                    </template>
                                </vxe-toolbar>
                            </template>
                        </vxe-grid>
                    </div>
                </template>
            </vxe-modal>
        </vxe-pulldown>
    </div>
</template>

<script>
export default {
    name: "vDownDialog",
    components: {
        VirtualNode: () => import('../../custom/VirtualNode'),
    },
    props: {
        params: Object,
        remoteMethod: Function,
        tableColumn: {
            type: Array,
            default() {
                return [];
            },
        },
        modelTableColumn: {
            type: Array,
            default: null,
        },
        size: {
            type: String,
            default() {
                return "mini";
            },
        },
        title: {
            type: String,
            default() {
                return "选择";
            },
        },
        dHeight: {
            type: String,
            default() {
                return '70vh';
            },
        },
        dWidth: {
            type: String,
            default() {
                return '80%';
            },
        },
        dLeft: {
            type: Function,
            default: null,
        },
        tableStyle: {
            type: Object,
            default: null,
        },
        dButtons: {
            type: Function,
            default: null,
        },
    },
    watch: {
        //vue的监听事件
        tableData: function () {
            this.setCurrentRow();
        },
    },
    data() {
        let $this = this;
        return {
            searchVal: "",
            row: null,
            column: null,
            tableData: [],
            loading: false,
            modalVisible: false,
            tablePage: {
                total: 0,
                currentPage: 1,
                pageSize: 10,
            },
            time: "",
        };
    },
    computed: {
        gridStyle() {
            let style = {
                flex: 1,
            };
            if (this.tableStyle) {
                style = $.extend({}, style, this.tableStyle);
            }
            return style;
        },
        realModelTableColumn() {
            if (this.modelTableColumn && this.$utils.isNotEmpty(this.modelTableColumn)) {
                return (this.modelTableColumn || []).map(item => $.extend({}, item));
            }
            return (this.tableColumn || []).map(item => $.extend({}, item));
        },
    },
    created() {
        this.load();
        window.addEventListener("keydown", this.setHeadPosition, true);
    },
    methods: {
        async load() {
            let $this = this;
            const {row, column} = this.params;
            this.row = row;
            this.column = column;
            this.searchVal = row[column.property];
            this.getData(this.modalVisible);
        },
        getData(visible, current = true) {
            let $this = this;
            const { row } = $this.params;
            let xGrid = $this.$refs.xGrid;
            let currentPage = this.tablePage.currentPage,
                pageSize = this.tablePage.pageSize;
            if (this.time) clearTimeout(this.time);
            $this.loading = true;
            this.time = setTimeout(() => {
                $this.remoteMethod({
                    row,
                    searchValue: $this.searchVal,
                    pageNo: currentPage,
                    pageSize,
                    visible,
                }).then((res) => {
                    $this.loading = false;
                    $this.tableData = res.data || [];
                    $this.tablePage.total = res.page.totalRows;
                    $this.tablePage.pages = res.page.pages;
                    $this.setCurrentRow(current);
                });
            }, 500);
        },
        setCurrentRow(current = true) {
            if (current) {
                if (!this.modalVisible) {
                    if (this.tableData.length) {
                        this.$refs.xDown.showPanel();
                    } else this.$refs.xDown.hidePanel();
                }
            }
            setTimeout(() => {
                if (this.$refs.xGrid) {
                    this.$refs.xGrid.setCurrentRow(this.tableData[0]);
                    this.$refs.xGrid.focus();
                }
            }, 100);
        },
        clickEvent() {
            if (this.tableData.length) {
                this.$refs.xDown.showPanel();
                this.setCurrentRow();
            }
        },
        clickEvent1() {
            if (this.tableData.length) {
                this.$refs.xDown.showPanel();
                this.setCurrentRow();
            }
        },
        keyupEvent() {
            const {row, column} = this;
            const cellValue = row[column.property];
            if (cellValue !== this.searchVal) {
                this.searchVal = cellValue;
                this.getData(this.modalVisible);
            }
        },
        suffixClick() {
            this.$refs.xDown.hidePanel();
            setTimeout(() => {
                this.modalVisible = true;
                this.getData(this.modalVisible);
                this.setCurrentRow();
            }, 10);
        },
        pageChangeEvent({currentPage, pageSize}) {
            this.tablePage.currentPage = currentPage;
            this.tablePage.pageSize = pageSize;
            this.getData(this.modalVisible);
        },
        selectEvent(params) {
            const {row, column} = this;
            this.$emit("event", {
                type: "cellClick",
                row,
                column,
                params,
            });
            this.$refs.xDown.hidePanel();
            this.modalVisible = false;
        },
        setHeadPosition(e) {
            let $this = this;
            if ($(e.target).hasClass('vxe-input--inner')) {
                e.stopPropagation();
                if (e.code === "Enter" || e.code === 'NumpadEnter') {
                    $this.getData($this.modalVisible, false);
                }
                return;
            }
            let currentPage = this.tablePage.currentPage,
                pages = this.tablePage.pages;
            this.noGet = false;
            let xGrid = $this.$refs.xGrid;
            if (e.code === "ArrowLeft") {
                // 左
                if (currentPage > 1) currentPage--;
                else if (currentPage === 1) {
                    this.noGet = true;
                }
                this.tablePage.currentPage = currentPage;
                if (!this.noGet) this.getData(this.modalVisible);
            } else if (e.code === "ArrowRight") {
                // 右;
                if (currentPage < pages) currentPage++;
                else if (currentPage === pages) {
                    this.noGet = true;
                }
                this.tablePage.currentPage = currentPage;
                if (!this.noGet) this.getData(this.modalVisible);
            } else if (e.code === "Enter" || e.code === 'NumpadEnter') {
                //回车
                console.log(xGrid);
                if (xGrid) {
                    this.selectEvent({
                        row: xGrid.getCurrentRecord(),
                        $grid: xGrid,
                        $table: xGrid.$refs.xTable,
                    });
                }
            }
        },
    },
    destroyed() {
        window.removeEventListener("keydown", this.setHeadPosition, true);
    },
};
</script>

<style lang="less" rel="stylesheet/less" scoped>
.edit-down-pulldown {
    width: 100%;
}

.edit-down-wrapper {
    // width: 600px;
    height: 300px;
    background-color: #fff;
    border: 1px solid #dcdfe6;
    box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
}
</style>
